package com.web.util;

//JDBC工具类

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class JDBCUtils {
    //执行增删改操作
    public static int update(String sql,Object... args){
        //获得命令对象
        try (Connection conn = DataSourceUtils.getConnection()){
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            //设置参数
            for (int i = 0 ; i<args.length;i++){
                preparedStatement.setObject(i+1,args[i]);
            }
            //执行命令
            int rows = preparedStatement.executeUpdate();
            return rows;

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
    public static <T> List<T> query(Class<T> clazz,String sql,Object... args){
        try (Connection conn = DataSourceUtils.getConnection()){
            //获取命令对象
            PreparedStatement preparedStatement = conn.prepareStatement(sql);
            //设置参数
            for(int i = 0;i< args.length;i++){
                preparedStatement.setObject(i+1,args[i]);
            }
            //创建List合集
            List<T> list = new ArrayList<>();
            //执行命令
            ResultSet resultSet = preparedStatement.executeQuery();
            //遍历结果
            while(resultSet.next()){
                //创建对象
                T t = clazz.newInstance();
                //通过反射来读取类的所有属性
                Field[] fields = clazz.getDeclaredFields();
                //遍历所有属性，给属性赋值
                for (Field field:fields){
                    //通过属性名获得结果集中的值
                    Object value = resultSet.getObject(field.getName());
                    //修改属性访问权
                    field.setAccessible(true);
                    //通过属性，set(对象，值)给属性赋值
                    field.set(t,value);
                }
                //添加对象到集合
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
